﻿using System;
using System.Collections.Generic;
using System.Text;

namespace MLForgeSharp.Models.SupervisedLearningModels.NeuralNet
{
    public class Perceptron
    {
        private double[] weights; // 权重向量
        private double bias; // 偏置项
        private double learningRate; // 学习率

        public Perceptron(int inputSize, double learningRate = 0.1)
        {
            this.learningRate = learningRate;
            this.weights = new double[inputSize];
            this.bias = 0.0;

            // 初始化权重和偏置
            Random rand = new Random();
            for (int i = 0; i < inputSize; i++)
            {
                weights[i] = rand.NextDouble() - 0.5;
            }
            bias = rand.NextDouble() - 0.5;
        }

        // 激活函数（阶跃函数）
        private int Activation(double x)
        {
            return x >= 0 ? 1 : 0;
        }

        // 预测
        public int Predict(double[] inputs)
        {
            double sum = bias;
            for (int i = 0; i < inputs.Length; i++)
            {
                sum += inputs[i] * weights[i];
            }
            return Activation(sum);
        }

        // 训练模型
        public void Train(double[][] inputs, int[] targets, int epochs = 100)
        {
            for (int epoch = 0; epoch < epochs; epoch++)
            {
                for (int i = 0; i < inputs.Length; i++)
                {
                    double[] input = inputs[i];
                    int target = targets[i];

                    // 预测
                    int prediction = Predict(input);

                    // 计算误差
                    int error = target - prediction;

                    // 更新权重和偏置
                    for (int j = 0; j < weights.Length; j++)
                    {
                        weights[j] += learningRate * error * input[j];
                    }
                    bias += learningRate * error;
                }
            }
        }
    }

    // 示例程序
    public class PerceptronExample
    {
        public PerceptronExample()
        {
            // 示例数据
            double[][] inputs = new double[][]
        {
            new double[] { 0, 0 },
            new double[] { 0, 1 },
            new double[] { 1, 0 },
            new double[] { 1, 1 }
        };

            int[] targets = { 0, 0, 0, 1 }; // 目标类别

            // 创建模型
            Perceptron model = new Perceptron(inputSize: 2, learningRate: 0.1);

            // 训练模型
            model.Train(inputs, targets, epochs: 100);

            // 预测
            double[] testInput = { 1, 1 };
            int predictedClass = model.Predict(testInput);

            System.Console.WriteLine("预测类别: " + predictedClass);
        }
    }
}
